package com.suntop.carousel.qlmediaplay.video.cover;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.suntop.carousel.qlmediaplay.field.Field_Scale;
import com.suntop.carousel.qlmediaplay.tools.VideoFrameTool;
import com.suntop.carousel.qlmediaplay.video.player.ICoverView;


import java.io.File;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.constraintlayout.widget.ConstraintSet;

import static com.bumptech.glide.load.resource.bitmap.VideoDecoder.FRAME_OPTION;

@SuppressLint("NewApi")
public class ImageCover extends AppCompatImageView implements ICoverView {


    private RequestOptions requestOptions;
    private Bitmap mBitmap;
    private int screenWith;
    private int screenHeight;


    public ImageCover(@NonNull Context context) {
        this(context, null);
    }

    public ImageCover(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ImageCover(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }


    @Override
    public void showVisibility(int visibility) {
        if (visibility == GONE) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    setVisibility(GONE);
                }
            }, 50);
        } else {
            setVisibility(visibility);
        }
    }



    @Override
    public void showScaleType(int type) {
        switch (type) {
            default:
                this.setScaleType(ScaleType.FIT_CENTER);
                break;
            case Field_Scale.Scale_Match:
                this.setScaleType(ScaleType.FIT_XY);
                break;
            case Field_Scale.Scale_Crop:
                this.setScaleType(ScaleType.CENTER_CROP);
                break;
        }
    }

    /**
     * 显示首页
     * @param url
     */

    @Override
    public void showUrl(String url) {
        if (!TextUtils.isEmpty(url)&&isCanLoad()) {
            String absolutePath = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath();
            VideoFrameTool.getInstance().loadFFmengFirst(url, absolutePath
                    , 1, new VideoFrameTool.OnLoadVideoImageListener() {
                        @Override
                        public void onLoadImage(File file) {
                            if (file!=null&&isCanLoad())
                            Glide.with(getContext())
                                    .load(file)
                                    .apply(requestOptions)
                                    .into(ImageCover.this);
                        }
                    });

        }
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private boolean isCanLoad(){
        if (getContext()==null){
            return false;
        }
        if (getContext() instanceof Activity){
            boolean destroyed = ((Activity) getContext()).isDestroyed();
            return !destroyed;
        }
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void showBitmap(Bitmap bitmap) {
        if (getContext() != null && bitmap != null&&isCanLoad()) {
            Glide.with(getContext())
                    .load(bitmap)
                    .apply(requestOptions)
                    .into(this);
            if (mBitmap != null) {
                if (!mBitmap.isRecycled())
                    mBitmap.recycle();
                mBitmap = null;
            }
            mBitmap = bitmap;
            this.requestLayout();
        }
    }





    @Override
    public void initView() {
        requestOptions = new RequestOptions()
                .error(getDrawable())
                .placeholder(getDrawable())
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
//                .dontAnimate()
//                .dontTransform();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        screenHeight=MeasureSpec.getSize(heightMeasureSpec);
        screenWith=MeasureSpec.getSize(widthMeasureSpec);
    }
    @Override
    public View coverView() {
        return this;
    }

    @Override
    public void release() {
        if (getContext() != null)
            try {
                Glide.with(getContext())
                        .clear(this);
            }catch (Exception e){
                e.fillInStackTrace();
            }
        if (mBitmap != null) {
            if (!mBitmap.isRecycled())
                mBitmap.recycle();
            mBitmap = null;
        }

    }
}
